package com.atguigu.crowd.mvc.config;

import com.autguigu.crowd.constant.CrowdConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * spring-security配置类
 *
 * @author wmb
 *
 * @since 2021-1-28
 */
@Configuration
@EnableWebSecurity
// 启用全局方法权限控制功能，并且设置prePostEnabled = true。保证@PreAuthorize、@PostAuthorize、@PreFilter、@PostFilter生效
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SuppressWarnings("all")
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("crowdUserDetailService")
    private UserDetailsService userDetailsService;

    /*
    在这里声明，无法在xxxService中装配
    @Bean
    private BCryptPasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }*/

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        // 临时使用内存版登录的模式测试代码
//        builder
//                .inMemoryAuthentication()
//                .passwordEncoder(new BCryptPasswordEncoder())
//                .withUser("tom")
//                .password(new BCryptPasswordEncoder().encode("123123"))
//                .roles("ADMIN");

        // 正式功能中使用j基于数据库的认证
        builder
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security
                .authorizeRequests()    // 对请求进行授权
                .antMatchers("/admin/to/login/page.html", "/bootstrap/**", "/crowd/**",
                        "/css/**", "/fonts/**", "/img/**", "/jquery/**", "/layer/**", "/script/**",
                        "/ztree/**")    // 针对登录页、静态资源等
                .permitAll()            // 无条件访问
                .anyRequest()           // 其他任意请求
                .authenticated()        // 认证后访问
                .antMatchers("/admin/get/page.html")    // 针对分页显示admin设定访问控制
//                .hasRole("经理")          // 要求具备经理角色
                .access("hasRole('经理') AND hasAuthority('user:get')")   // 要求具备"经理"角色和"user:get"权限二者之一
                .anyRequest()           // 其他任意请求
                .authenticated()        // 认证后访问
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        request.setAttribute("exception", new Exception(CrowdConstant.MESSAGE_ACCESS_DENIED));
                        request.getRequestDispatcher("/WEB-INF/system-error.jsp").forward(request, response);
                    }
                })
                .and()
                .csrf()                 // 放跨站请求伪造功能
                .disable()              // 禁用
                .formLogin()            // 开启表单登录功能
                .loginPage("/admin/to/login/page.html")    //指定登录页面
                .loginProcessingUrl("/security/do/login.html")  // 指定处理登录请求地址
                .permitAll()
                .defaultSuccessUrl("/admin/to/main/page.html")  // 指定登录成功后前往的地址
                .usernameParameter("loginAccount")      // 账号的请求参数名称
                .passwordParameter("password")          // 密码的请求参数名称
                .and()
                .logout()                               // 开启退出登录功能
                .logoutUrl("/security/do/logout.html")  // 指出退出登录功能
                .logoutSuccessUrl("/admin/to/login/page.html")  // 指定推出成功以后前往的地址
        ;
    }
}
